//
//  CZPopMenuView.m
//  小和微博
//
//  Created by 董晓合 on 15/2/21.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "CZPopMenuView.h"

@implementation CZPopMenuView

static UIWindow *_window;
static dismissBlack _dismiss;
static UIViewController *_contentVc;

+ (void)popFrom:(UIView *)fromView content:(UIView *)content dismiss:(dismissBlack)dismiss {

    [self popFrom:fromView.frame inView:fromView.superview content:content dismiss:dismiss];
}

+ (void)popFrom:(CGRect)fromRect inView:(UIView *)inView content:(UIView *)content dismiss:(dismissBlack)dismiss {
    
    _dismiss = [dismiss copy];
    
//    1.创建window
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.hidden = NO;
    _window.windowLevel = UIWindowLevelAlert;
    
    // 2.创建蒙版
    UIButton *cover = [[UIButton alloc] init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    [_window addSubview:cover];
    
//   3.创建菜单
    UIImageView *menuView = [[UIImageView alloc] init];
    menuView.userInteractionEnabled = YES;
    UIImage *image = [UIImage imageNamed:@"popover_background"];
    menuView.image = image;
    [cover addSubview:menuView];
    
    //   添加内容视图
    content.x = 15;
    content.y = 18;
    [menuView addSubview:content];
    
    //    设置菜单容器的frame
    CGFloat menuViewW = CGRectGetMaxX(content.frame) + content.x;
    CGFloat menuViewH = CGRectGetMaxY(content.frame) + content.y;
    menuView.frame = CGRectMake(0, 0, menuViewW, menuViewH);
    
//    获取需要指向控件的frame
    CGRect resultFrame = [_window convertRect:fromRect fromView:inView];
//    设置菜单Y值
    menuView.y = CGRectGetMaxY(resultFrame);

    menuView.centerX = resultFrame.origin.x + (resultFrame.size.width * 0.5);
    
    // 6.显示菜单
    _window.hidden = NO;
 
}
+ (void)coverClick:(UIButton *)btn {
    
    _window = nil;
    _contentVc = nil;
//    通知调用者
    if (_dismiss != nil) {
        _dismiss();
    }
}


+ (void)popFrom:(UIView *)fromView contentVc:(UIViewController *)contentVc dismiss:(dismissBlack)dismiss {
//  保命
    _contentVc = contentVc;
    
//    显示
    [self popFrom:fromView content:_contentVc.view dismiss:dismiss];
}


@end
